<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 自定义字段管理
 */
class CustomField extends Backend
{
    protected $model = null;
    protected $noNeedRight = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\scanwork\CustomField;
    }

    /**
     * 检查字段唯一性
     */
    public function check_unique()
    {
        // 支持GET和POST两种方式获取参数
        $field = $this->request->param('field') ?: $this->request->post('field');
        $value = $this->request->param('value') ?: $this->request->post('value');
        $id = $this->request->param('id', 0) ?: $this->request->post('id', 0);
        
        // 如果value为空，尝试从POST的row数组中获取
        if (empty($value)) {
            $postData = $this->request->post();
            if (isset($postData['row']) && isset($postData['row'][$field])) {
                $value = $postData['row'][$field];
            }
        }
        
        // 调试信息
        \think\Log::info('CustomField check_unique params: ' . json_encode([
            'field' => $field,
            'value' => $value,
            'id' => $id,
            'get' => $this->request->get(),
            'post' => $this->request->post()
        ]));
        
        if (empty($field) || empty($value)) {
            $this->error('参数错误: field=' . $field . ', value=' . $value);
        }
        
        $where = [$field => $value];
        if ($id > 0) {
            $where['id'] = ['neq', $id];
        }
        
        $exists = $this->model->where($where)->find();
        
        if ($exists) {
            $this->error('该值已存在');
        } else {
            $this->success('验证通过');
        }
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 处理选项配置
                if (isset($params['field_options']) && is_array($params['field_options'])) {
                    $params['field_options'] = json_encode($params['field_options'], JSON_UNESCAPED_UNICODE);
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // 获取行业列表
        $industryList = Db::name('scanwork_industry_config')->where('status', 'normal')->select();
        $this->view->assign('industryList', $industryList);
        
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                // 处理选项配置
                if (isset($params['field_options']) && is_array($params['field_options'])) {
                    $params['field_options'] = json_encode($params['field_options'], JSON_UNESCAPED_UNICODE);
                }
                
                $result = false;
                Db::startTrans();
                try {
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        
        // JSON字段解析
        if (!empty($row['field_options'])) {
            $row['field_options'] = json_decode($row['field_options'], true);
        }
        
        // 获取行业列表
        $industryList = Db::name('scanwork_industry_config')->where('status', 'normal')->select();
        $this->view->assign('industryList', $industryList);
        
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk = $this->model->getPk();
            $list = $this->model->where($pk, 'in', $ids)->select();
            
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    $count += $item->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    
    /**
     * 获取指定模块的自定义字段
     */
    public function getFieldsByModule()
    {
        $moduleName = $this->request->param('module_name');
        $industryCode = $this->request->param('industry_code');
        
        if (!$moduleName) {
            $this->error('模块名称不能为空');
        }
        
        $where = ['module_name' => $moduleName, 'status' => 'normal'];
        if ($industryCode) {
            $where['industry_code'] = $industryCode;
        }
        
        $fields = $this->model->where($where)->where('is_visible', 1)->order('sort', 'asc')->select();
        
        return json(['code' => 1, 'data' => $fields]);
    }
}

